
extern "C" {
  #include "ringbuffer.h"
}

#include <gtest/gtest.h>


TEST(RingBufferTest, create_destroy) {
  ring_buffer_t *buf = ring_buffer_new(1024);
  EXPECT_TRUE(buf != nullptr);
  ring_buffer_free(buf);
}

TEST(RingBufferTest, AddData) {
  ring_buffer_t *buf = ring_buffer_new(1024);
  EXPECT_TRUE(buf != nullptr);

  char data[] = "Hello, World!";
  uint32_t datlen = strlen(data);

  int result = ring_buffer_add(buf, data, datlen);
  EXPECT_EQ((int)datlen, result);
  EXPECT_EQ((int)datlen, (int)ring_buffer_len(buf));
  ring_buffer_free(buf);
}

TEST(RingBufferTest, RemoveData) {
  ring_buffer_t *buf = ring_buffer_new(1024);
  EXPECT_TRUE(buf != NULL);

  char data2[] = "Hello, World!";
  uint32_t datlen2 = strlen(data2);

  // 先添加数据
  int add_result = ring_buffer_add(buf, data2, datlen2);
  EXPECT_EQ((int)datlen2, add_result);

  // 然后读取数据
  char read_data[1024];
  int remove_result = ring_buffer_remove(buf, read_data, datlen2);

  EXPECT_EQ(datlen2, remove_result);
  EXPECT_STREQ(data2, read_data);
  EXPECT_EQ(0, ring_buffer_len(buf));

  ring_buffer_free(buf);
}

TEST(RingBufferTest, EdgeCase) {
  ring_buffer_t *buf = ring_buffer_new(4);
  EXPECT_TRUE(buf != NULL);

  // 测试添加超过缓冲区大小的数据
  char large_data[] = "This is a large data string";
  uint32_t large_datlen = strlen(large_data);
  int add_result2 = ring_buffer_add(buf, large_data, large_datlen);
  EXPECT_EQ(0, add_result2); // 应该添加失败

  // 测试从空缓冲区读取数据
  char read_data2[1024];
  int remove_result2 = ring_buffer_remove(buf, read_data2, 10);
  EXPECT_EQ(0, remove_result2); // 应该读取失败

  // 测试添加和读取部分数据
  char small_data[] = "Hi";
  uint32_t small_datlen = strlen(small_data);
  add_result2 = ring_buffer_add(buf, small_data, small_datlen);
  EXPECT_EQ(small_datlen, add_result2);

  remove_result2 = ring_buffer_remove(buf, read_data2, 1);
  EXPECT_EQ(1, remove_result2);
  EXPECT_EQ('H', read_data2[0]);

  ring_buffer_free(buf);
}

TEST(RingBufferTest, Search) {
  ring_buffer_t *buf = ring_buffer_new(1024);
  EXPECT_TRUE(buf != NULL);

  // 添加一些数据
  char data[] = "Hello, World! This is a test string for search functionality.";
  uint32_t datlen = strlen(data);
  int add_result = ring_buffer_add(buf, data, datlen);
  EXPECT_EQ((int)datlen, add_result);

  // 搜索存在的字符串
  int search_result = ring_buffer_search(buf, "World", 5);
  // assert(search_result != buf->tail); // 应该找到
  EXPECT_NE(search_result, buf->tail);

  // 搜索不存在的字符串
  search_result = ring_buffer_search(buf, "NotFound", 8);
  // assert(search_result == buf->tail); // 应该找不到
  EXPECT_EQ(search_result, buf->tail);

  ring_buffer_free(buf);
}